﻿/*-----------------------------------------------------------------------
 * <copyright file="AccountRolesControl.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang jun</author>
 * <summary>
 *             权限分配
 *     引用服务：WCFServers.WCFAccountsRef
 *     服务功能：数据的更新，查询
 *    
 *     引用服务：WCFLog4Ref.WCFLog4Client
 *     服务功能：记录日志
 * 
 * 作成日：05/21/2010
 * </summary>
 *----------------------------------------------------------------------- 
 */
namespace Orid.Management.Statistics.OperatorUnitMangement.CompetenceSetPaeg.AccountRoles
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFAccountsRef;

    /// <summary>
    /// 权限分配
    /// AccountRolesControl
    /// </summary>
    public partial class AccountRolesControl : UserControl
    {
        #region  全局变量

        /// <summary>
        /// 服务定义
        /// WCFAccountsClient
        /// </summary>
        private WCFServers.WCFAccountsRef.WCFAccountsClient client;       
        
        /// <summary>
        /// 日志服务定义
        /// WCFLog4Client
        /// </summary>
        private WCFLog4Ref.WCFLog4Client wcfLogClient;

        /// <summary>
        /// 消息子窗口
        /// MessageBox
        /// </summary>
        private childWindow.MessageBox messbox;
      
        /// <summary>
        /// 分页控件
        /// PagedCollectionView
        /// </summary>
        private PagedCollectionView pcv;
      
        /// <summary>
        /// 帐号编辑子窗体
        /// accountREditChild
        /// </summary>
        private AccountRolesEditShowChild accountREditChild;

        /// <summary>
        /// combobox
        /// 显示所有权限
        /// </summary>
        private List<string> comList;

        #endregion  全局变量

        /// <summary>
        /// 构造函数
        /// AccountRolesControl
        /// </summary>
        public AccountRolesControl()
        {
            InitializeComponent();

            // 引用主题
            ((App)Application.Current).SetTheme((Grid)LayoutRoot);

            this.dgAccountRoles.HeadersVisibility = DataGridHeadersVisibility.All;//同时显示DataGrid的行头与列头

            this.client = Wcf.Service.Accounts;

            this.wcfLogClient = Wcf.Service.Log4;

            this.accountREditChild = new AccountRolesEditShowChild();

            this.comList = new List<string>();

            messbox = new childWindow.MessageBox(); 

            // 显示所有有权限的用户（服务委托）
            this.client.AccountRolesListCompleted += new EventHandler<AccountRolesListCompletedEventArgs>(this.Client_AccountRolesListCompleted);

            // 取得现有权限列表（服务委托）
            this.client.RolesListCompleted += new EventHandler<WCFServers.WCFAccountsRef.RolesListCompletedEventArgs>(this.Client_RolesListCompleted);
            this.client.RolesListAsync();
            
            // 页面载入
            this.Loaded += new RoutedEventHandler(this.AccountRolesControl_Loaded);

            // 子窗体关闭事件(委托)
            this.accountREditChild.Closed += new EventHandler(this.AccountREditChild_Closed);
            
            // datagrid的分组事件
            this.dgAccountRoles.LoadingRowGroup += new EventHandler<DataGridRowGroupHeaderEventArgs>(this.DgAccountRoles_LoadingRowGroup);
        }
     
        #region 页面载入
        /// <summary>
        /// 页面载入
        /// AccountRolesControl_Loaded
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void AccountRolesControl_Loaded(object sender, RoutedEventArgs e)
        {
           try
            {
                if (this.dgAccountRoles.ItemsSource != null)
                {
                    this.dgAccountRoles.ItemsSource = null;
                }

                this.client.AccountRolesListAsync();
            }
            catch (Exception ex) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +"AccountManagementControl" + ex.Message.ToString());
                Common.FunctionList.FunctionClass.ShowMessageBox(
                    this.messbox,
                    1,
                    "提示",
                    ex.Message.ToString(),
                    Colors.Gray,
                    true,
                    Visibility.Visible,
                    Visibility.Collapsed);
                return;
            }            
        }
        #endregion 页面载入

        #region  分组
        /// <summary>
        /// 显示所有有权限的用户（服务实现）
        /// Client_AccountRolesListCompleted
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of AccountRolesListCompletedEventArgs</param>
        private void Client_AccountRolesListCompleted(object sender, AccountRolesListCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        this.pcv = null;
                        this.pcv = new PagedCollectionView(e.Result);

                        // 安条件分组
                        this.pcv.GroupDescriptions.Clear();
                        this.pcv.GroupDescriptions.Add(new PropertyGroupDescription("RoleName"));

                        this.dgAccountRoles.DataContext = null;
                        this.dgAccountRoles.DataContext = this.pcv;
                    }
                    else
                    {
                        this.dgAccountRoles.ItemsSource = null;
                        throw (new Exception("没有可显示的分组数据"));
                    }
                }
                else 
                {
                    throw (new Exception(e.Error.Message.ToString()));
                }
            }
            catch (Exception ex) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + "AccountManagementControl" + ex.Message.ToString());

                Common.FunctionList.FunctionClass.ShowMessageBox(
                this.messbox,
                1,
                "提示",
                ex.Message.ToString(),
                Colors.Gray,
                true,
                Visibility.Visible,
                Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// datagrid的分组事件
        /// DgAccountRoles_LoadingRowGroup
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of DataGridRowGroupHeaderEventArgs</param>
        private void DgAccountRoles_LoadingRowGroup(object sender, DataGridRowGroupHeaderEventArgs e)
        {
            // 让分组标示，显示指定名称;
            e.RowGroupHeader.PropertyName = "身份";
      
            // 设置分组条的颜色
            e.RowGroupHeader.Background = new SolidColorBrush(Colors.DarkGray);
        }

        #endregion  分组

        #region 显示子窗体
        /// <summary>
        /// DataGrid上的编辑按钮
        /// BtnEdit_Click
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void BtnEdit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.accountREditChild.tbUseName.Text = ((Button)sender).Tag.ToString();
                if (ClientDataList.ClientCombboxList.Count > 0)
                {
                    // 数据源绑定
                    this.accountREditChild.cmBox.ItemsSource = this.comList;

                    // 不选中任何项
                    this.accountREditChild.cmBox.SelectedIndex = -1;

                    // 显示权限子窗体
                    this.accountREditChild.Show();
                }
                else
                {
                    throw new Exception("没有可以显示的权限");
                }
            }
            catch (Exception ex) 
            {
                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.messbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }           
        }
        #endregion 显示子窗体

        #region Combobox数据源 取得现有权限列表（服务实现）
        /// <summary>
        /// 取得现有权限列表（服务实现）
        /// Client_RolesListCompleted
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RolesListCompletedEventArgs</param>
        private void Client_RolesListCompleted(object sender, RolesListCompletedEventArgs e)
        {
            // 把从服务端取得的数据，转变成本地数据
            try
            {
                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        ClientDataList.ClientCombboxList.Clear();
                        this.comList.Clear();

                        foreach (RolesCombboxDataList item in e.Result)
                        {
                            ClientDataList.ClientCombboxList.Add(
                                            new ClientCombboxData()
                                            {
                                                RoleID = item.RoleID.Trim().ToString(),
                                                RoleName = item.RoleName.Trim().ToString()
                                            });
                          
                            // 把权限的名称加入到列表中
                            // 不显示ADMINISTRATOR
                            if (!item.RoleName.Trim().ToString().ToUpper().Equals("ADMINISTRATOR"))
                            {
                                this.comList.Add(item.RoleName.Trim().ToString());
                            }
                        }

                        ////List<string> comlit = (from com in comList 
                        ////                    where com[0].ToString()!="administrator"
                        ////                    select com).Distinct().ToList<string>();
                    }
                    else
                    {
                        throw (new Exception("初使化权限列表未成功！"));
                    }
                }
                else 
                {
                    throw (new Exception(e.Error.Message.ToString()));
                }
            }
            catch (Exception ex) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + " AccountManagementControl" + ex.Message.ToString());
                Common.FunctionList.FunctionClass.ShowMessageBox(
                    this.messbox,
                    1,
                    "提示",
                    ex.Message.ToString(),
                    Colors.Gray,
                    true,
                    Visibility.Visible,
                    Visibility.Collapsed);
                return;
            }
        }
        #endregion Combobox数据源 取得现有权限列表（服务实现）

        #region 子窗体关闭事件
        /// <summary>
        /// 子窗体关闭事件
        /// AccountREditChild_Closed
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void AccountREditChild_Closed(object sender, EventArgs e)
        {          
            try
            {
                if (this.accountREditChild.cmBox.SelectedIndex == -1)
                {
                    return; 
                }

                this.accountREditChild = (AccountRolesEditShowChild)sender;
                if (this.accountREditChild.DialogResult == true)
                {
                    List<string> roleIDList = new List<string>();

                    // 得到权限对应的ID
                    if (this.accountREditChild.cmBox.SelectedIndex != -1)
                    {
                        roleIDList = (from getRoleid in Common.FunctionList.ClientDataList.ClientCombboxList
                                      where getRoleid.RoleName == accountREditChild.cmBox.SelectedItem.ToString()
                                      select getRoleid.RoleID).ToList<string>();
                    }

                    if (roleIDList.Count > 0)
                    {
                        // 更新权限
                        this.client.UpeateOneAccountRolesAsync(this.accountREditChild.tbUseName.Text.Trim(), roleIDList[0].ToString().Trim());

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr + "更新权限操作成功");

                        // 重新载入
                        this.client.AccountRolesListAsync();
                    }
                }
            }
            catch (Exception ex) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + " AccountManagementControl" + ex.Message.ToString());
                
                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.messbox,
                   1,
                   "权限更新没有成功",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #endregion  子窗体关闭事件
    }
}
